﻿using System;
using System.Data;
using AccessControl.Data.Models;
using System.Data.SqlClient;
using System.Collections.Generic;
using AccessControl.Contracts.Models;
using AccessControl.Contracts.Data;

namespace AccessControl.DataManagers.Tables.Managers
{
    /// <summary>
    /// Base class for all tables managers 
    /// </summary>
    /// <typeparam name="T">The type of the item</typeparam>
    abstract class TableManager<T> : IDataManager<T> where T : IModel
    {
        #region Abstracts

        public abstract void Create(SqlConnection connection);
		public abstract void Initialize(SqlConnection connection);

		public abstract bool Add(T item);
		public abstract bool Update(T item);
		public abstract bool Delete(T item);
		public abstract bool FillList(IList<T> items);

		#endregion

		#region Protected Members

		protected int GetRowsCount(SqlConnection connection, string tableName)
		{
			object o;
			SqlCommand countCommand = new SqlCommand(string.Format("SELECT COUNT(*) FROM {0}", tableName), connection);
			o = countCommand.ExecuteScalar();

			try { return Convert.ToInt32(o); }
			catch { return 0; }
		}

		protected int GetHighestId(SqlConnection connection, string tableName, string idColName)
		{
			object o;

			if (GetRowsCount(connection, tableName) == 0)
				return 0;

			SqlCommand countCommand = new SqlCommand(string.Format("SELECT MAX({0}) FROM {1}", idColName, tableName), connection);
			o = countCommand.ExecuteScalar();
			
			try		{ return Convert.ToInt32(o); }
			catch	{ return 0; }
		}

		#endregion
	}
}
